package pers.xhh.shopapi.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import pers.xhh.shopapi.annotation.UserLoginToken;
import pers.xhh.shopapi.common.Mi;
import pers.xhh.shopapi.entity.to.role.MiRoleRightsTo;
import pers.xhh.shopapi.entity.to.role.MiRoleTo;
import pers.xhh.shopapi.service.MiRoleService;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @author wei-xhh
 * @date 2020-11-24
 */
@CrossOrigin
@RestController
@RequestMapping("/api/v1")
public class MiRoleController {

    @Autowired
    MiRoleService miRoleService;

    @UserLoginToken
    @GetMapping("/roles")
    public Mi listRoles(HttpServletRequest request){
        String authorization = request.getHeader("Authorization");
        return miRoleService.listRoles(authorization);
    }

    @UserLoginToken
    @PostMapping("/roles")
    public Mi insertRole(@Valid @RequestBody MiRoleTo miRoleTo){
        return miRoleService.saveRole(miRoleTo);
    }

    @UserLoginToken
    @GetMapping("/roles/{id}")
    public Mi getRoleById(@PathVariable("id") Integer id){
        return miRoleService.getRoleById(id);
    }

    @UserLoginToken
    @PutMapping("/roles/{id}")
    public Mi updateRoleById(@PathVariable("id") Integer id,
                             @Valid @RequestBody MiRoleTo miRoleTo){
        return miRoleService.updateRoleById(id, miRoleTo);
    }

    @UserLoginToken
    @DeleteMapping("/roles/{id}")
    public Mi deleteRoleById(@PathVariable("id") Integer id){
        return miRoleService.deleteRoleById(id);
    }

    @UserLoginToken
    @PostMapping("/roles/{id}/rights")
    public Mi updateRights(@PathVariable("id") Integer id,
                           @Valid @RequestBody MiRoleRightsTo miRoleRightsTo){
        return miRoleService.updateRights(id, miRoleRightsTo);
    }

    @UserLoginToken
    @DeleteMapping("/roles/{id}/rights/{rightId}")
    public Mi deleteRights(HttpServletRequest request,
                           @PathVariable("id") Integer id,
                           @PathVariable("rightId") Integer rightId){
        String authorization = request.getHeader("Authorization");
        return miRoleService.deleteRights(authorization,id, rightId);
    }

}
